<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="头像" prop="avatarUrl">
        <el-upload
          class="avatar-uploader"
          :action="getUploadUrl"
          :show-file-list="false"
          :with-credentials="true"
          :headers="header"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          field="file"
        >
          <img
            v-if="dataForm.avatarUrl"
            :src="dataForm.avatarUrl"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="地址" prop="specificAddr">

        <el-row>
          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select clearable v-model="formData.proId" @change="proChange">
                <el-option
                  v-for="item in proList"
                  :key="item.proId"
                  :label="item.proName"
                  :value="item.proId"
                >
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select
                clearable
                v-model="formData.cityId"
                @change="cityChange"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.cityId"
                  :label="item.cityName"
                  :value="item.cityId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select clearable v-model="formData.dirId" @change="dirChange">
                <el-option
                  v-for="item in dirList"
                  :key="item.disId"
                  :label="item.disName"
                  :value="item.disId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
                <el-input v-model="dataForm.specificAddr" placeholder="请填写具体地址(乡,镇,街道,门牌)"></el-input>

      </el-form-item>
      <el-form-item label="vip卡" prop="vipTag">
        <el-input v-model="dataForm.vipTag" placeholder="vip卡"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="dataForm.tel" placeholder="手机号"></el-input>
      </el-form-item>
    
      <el-form-item label="性别" prop="gender">
       <el-switch
          style="display: block"
          v-model="dataForm.gender"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="男"
          inactive-text="女"
          :active-value="1"
  :inactive-value="2"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="余额" prop="balance">
        <el-input v-model="dataForm.balance" placeholder="余额"></el-input>
      </el-form-item>
  
          <el-form-item label="状态" prop="status">
        <el-switch
          style="display: block"
          v-model="dataForm.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="激活"
          inactive-text="禁用"
          :active-value="0"
  :inactive-value="1"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="用户显示名" prop="realName">
        <el-input
          v-model="dataForm.realName"
          placeholder="用户显示名"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="dataForm.userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="dataForm.password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="微信小程序标识" prop="openId">
        <el-input
          v-model="dataForm.openId"
          placeholder="微信小程序标识"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import upload from "@/components/upload/singleUpload";
export default {
  components: { upload },
  data() {
    return {
      cityList: [],
      dirList: [],
      proList: [],
      formData: {proId:"",dirId:"",cityId: ""},
      header: {},
      imageUrl: "",
      visible: false,
      dataForm: {
        id: 0,
        userId: "",
        avatarUrl: "",
        addr: "",
        endorse: "",
        allowRefund: "",
        hallType: "",
        snack: "",
        movies: "",
        vipTag: "",
        tel: "",
        finallyLanding: "",
        lastLoginTime: "",
        gender: "",
        balance: "",
        createTime: "",
        platform: "",
        deleted: "",
        status: "",
        realName: "",
        userName: "",
        password: "",
        roleName: "",
        openId: "",
        specificAddr: "",
      },
      dataRule: {
        userId: [
          {
            required: true,
            message: "创建用户id：主要用于影院不能为空",
            trigger: "blur",
          },
        ],
        avatarUrl: [
          { required: true, message: "头像不能为空", trigger: "blur" },
        ],
        addr: [{ required: true, message: "地址不能为空", trigger: "blur" }],

        tel: [{ required: true, message: "手机号不能为空", trigger: "blur" }],

        gender: [
          {
            required: true,
            message: " 性别 0：未知、1：男、2：女不能为空",
            trigger: "blur",
          },
        ],

        realName: [
          { required: true, message: "用户显示名不能为空", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
  
      },
    };
  },
  mounted() {
  },
  watch: {
    "formData.proId": function (val) { 
        this.formData.proId=val;
    if(!this.addVar){
      this.formData.dirId = "";
        this.formData.cityId = "";
    }
          
   
      console.log("pro:"+this.formData.proId)
    },
    "formData.cityId": function (val) {
     if(!this.addVar){
        this.formData.dirId = "";
     }
      this.formData.cityId=val;
      console.log("city:"+this.formData.cityId)
    },
    "formData.dirId": function (val) {
      this.addVar=false
       this.formData.dirId=val;
      this.dataForm.addr = val;
      console.log("dir:"+this.dataForm.addr)
    },
  },
  methods: {
    beforeClose(){
       this.formData={};
    },
    getProList() {
      this.$http({
        url: this.$http.adornUrl(`/area/tprovince/list/100000`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.proList = data.dataList;
        console.log(data);
      });
    },
    getCityList() {
      this.$http({
        url: this.$http.adornUrl(`/area/tcity/list/` + this.formData.proId),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.cityList = data.dataList;
        console.log("city",data);
      });
    },
    getDirList() {
      this.$http({
        url: this.$http.adornUrl(
          `/area/tdistrict/list/` + this.formData.cityId
        ),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.dirList = data.dataList;
        console.log(data);
      });
    },
    // 操作人选中项发生变化
    proChange(val) {
      console.log("pro操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.proId, val);
        this.cityList = [];
        this.dirList = [];
        this.getCityList();
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        this.$set(this.formData, this.formData.proId, "");
      }
    },
    dirChange(val) {
      console.log("dir操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.dirId, val);
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        this.$set(this.formData, this.formData.dirId, "");
      }
    },
    // 操作人选中项发生变化
    cityChange(val) {
      console.log("city操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.cityId, val);
        this.dirList = [];
        this.getDirList();
        //清空
        // this.formData.operateName = obj.label
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        // this.formData.operateName = ''
              console.log("city操作空");
        this.$set(this.formData, this.formData.cityId, "");
      }
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.dataForm.avatarUrl = res.imageUrl;
    },
    beforeAvatarUpload(file) {
      var ca = document.cookie.split(";");
      console.log(ca[0].split("="));
      this.header.token = ca[0].split("=")[1];

      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      console.log(isJPG && isLt2M);
      return isJPG && isLt2M;
    },
    init(id) {
          this.getProList();

      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.formData={proId:"",dirId:"",cityId: ""};
        console.log("===========================")
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/cb/user/info/${this.dataForm.id}`),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log(data)
              this.dataForm.avatarUrl = data.user.avatarUrl;
              this.dataForm.addr = data.user.addr;
              this.dataForm.specificAddr= data.user.specificAddr
              this.dataForm.vipTag = data.user.vipTag;
              this.dataForm.tel = data.user.tel;
              this.dataForm.gender = data.user.gender;
              this.dataForm.balance = data.user.balance;
              this.dataForm.deleted = data.user.deleted;
              this.dataForm.status = data.user.status;
              this.dataForm.realName = data.user.realName;
              this.dataForm.userName = data.user.userName;
              this.dataForm.password = data.user.password;
              this.dataForm.openId = data.user.openId;
               this.getAddrs();
            }
          });

        
        }
      });
    },
    getAddrs(){
       this.$http({
            url: this.$http.adornUrl('/cb/user/addr/'+this.dataForm.addr),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.addVar=true;
              // console.log(data)
              this.getProList();
              console.log("1",data.addrs[0])
              this.formData.proId=data.addrs[0];
              this.getCityList();               
              console.log("2",data.addrs[1])

              this.formData.cityId=data.addrs[1];
              this.getDirList();
               console.log("3",data.addrs[2])
              this.formData.dirId=data.addrs[2];
            }
          });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/cb/user/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              avatarUrl: this.dataForm.avatarUrl,
              addr: this.dataForm.addr,
              vipTag: this.dataForm.vipTag,
              tel: this.dataForm.tel,
              gender: this.dataForm.gender,
              balance: this.dataForm.balance,
              createTime: this.dataForm.createTime,
              status: this.dataForm.status,
              realName: this.dataForm.realName,
              userName: this.dataForm.userName,
              password: this.dataForm.password,
              openId: this.dataForm.openId,
              specificAddr: this.dataForm.specificAddr
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
  computed: {
    getUploadUrl() {
      return window.SITE_CONFIG.baseUrl + "/cb/file/upload";
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>